const chalk = require('chalk');
const {STYLE_UNIT_TYPE, sort} = require('./const');
const hh = '\r\n';

const {sortArray} = require('../config/sort');

const map = sortArray.reduce((pre, cur, index) => {
    return {
        ...pre,
        [cur]: index
    }
}, {});

const map2 = sort.reduce((pre, cur, index) => {
    return {
        ...pre,
        [cur]: index
    }
}, {});

const sortFunc = (a, b) => {
    if (map[Object.keys(a)[0]] === undefined) {
        console.log(chalk.red('WARNING 请在sort.js中定义:', chalk.underline.red(Object.keys(a)[0]), '属性的顺序'))
    }
    if (map[Object.keys(a)[0]] > map[Object.keys(b)[0]]) {
        return 1;
    }
    return -1
};


const cssASObjectSort = (cssAst, sortUnit = true) => {
    if (sortUnit) {
        // 对 普通 import font_face等排序
        cssAst = cssAst.sort(function (a, b) {
            return map2[a.type] - map2[b.type]
        })
    }
    return cssAst.map((x) => {
        if (x.type === STYLE_UNIT_TYPE.ORDINARY || x.type === STYLE_UNIT_TYPE.PACE || x.type === STYLE_UNIT_TYPE.FONT_FACE) {
            return {
                type: x.type,
                selector: x.selector,
                rule: x.rule.sort(sortFunc)
            };
        }
        if (x.type === STYLE_UNIT_TYPE.IMPORT || x.type === STYLE_UNIT_TYPE.CHARSET || x.type === STYLE_UNIT_TYPE.COMMENT) {
            return {
                type: x.type,
                text: x.text
            };
        }
        return {
            type: x.type,
            ruleName: x.ruleName,
            childRule: (x.childRule || []).map(x => {
                return {
                    selector: x.selector,
                    rule: x.rule.sort(sortFunc)
                }
            })
        }

    });
};
module.exports.cssASObjectSort = cssASObjectSort;
